package com.bupt.user.service.impl;

import com.bupt.enums.ResultCode;
import com.bupt.exceptions.BusinessException;
import com.bupt.user.entity.User;
import com.bupt.user.mapper.UserMapper;
import com.bupt.user.service.UserService;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HttpSession httpSession;

    //验证登录信息，写入session
    @Override
    public User login(User user) {
        //判断是否缺少重要信息
        if (user.getUserId() == null || user.getPassword() == null) {
            throw new BusinessException(ResultCode.PARAM_IS_INVALID);
        }

        User selectUser = userMapper.selectOne(user);
        //判断用户名密码是否错误
        if (selectUser == null) {
            throw new BusinessException(ResultCode.USER_LOGIN_FAIL);
        }

        //保护用户隐私，不传递密码
        selectUser.setPassword(null);

        //如果正确就写入session
        httpSession.setAttribute(httpSession.getId(), selectUser);


        return selectUser;
    }

    @Override
    public User getUserByUserId(String userId) {
        User user = new User();
        user.setUserId(userId);
        return userMapper.selectOne(user);
    }

    @Override
    public void logout() {
        httpSession.removeAttribute(httpSession.getId());
    }

    @Override
    public User getUserFromSession() {
        String sessionId = httpSession.getId();
        System.out.println(sessionId);
        User user = (User) httpSession.getAttribute(httpSession.getId());
        if (user == null) {
            throw new BusinessException(ResultCode.SESSION_LOGIN_FAIL);
        }
        return user;
    }
}
